package s;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;
import cbir.Img;
import cbir.Rss;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.photos.SearchParameters;
import com.mysql.jdbc.Statement;

public class Random extends HttpServlet {

		private static final long serialVersionUID = 1L;
		
		private static final int numResults = 25;
		private Properties props;
		private String propsPath;

		public void init(ServletConfig config) throws ServletException {
				super.init(config);
				
				this.propsPath = this.getServletContext().getRealPath("/");
				this.props = new Properties();
				try {
					props.loadFromXML(new FileInputStream(propsPath + "properties.properties"));
				} catch (FileNotFoundException e) {e.printStackTrace();} 
				catch (IOException e) {e.printStackTrace();}
		}
	

		protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {			
			ArrayList<Img> imgs = new ArrayList<Img>();				
			int n = (int) (Math.random()*numResults+1);
			int obtainedFromDB = 0;
			
			Connection connection = null;
			try {
				Class.forName("com.mysql.jdbc.Driver");
				connection = DriverManager.getConnection(props.getProperty("DB_URL"), props.getProperty("DB_USER"), props.getProperty("DB_PASS"));
				Statement statement = (Statement) connection.createStatement();
				ResultSet rs = statement.executeQuery("SELECT Filename " +
						"FROM img " +
						"ORDER BY RAND() " +
						"LIMIT " + n +";");
				
				while(rs.next()){
					Img tmp = new Img(rs.getString("Filename"), "", "", "", req.getServerName(), req.getContextPath());
					imgs.add(tmp);
					obtainedFromDB++;
				}
			} 
			catch (SQLException e2) {e2.printStackTrace();} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			finally {
				try {connection.close();} 
				catch (SQLException e) {e.printStackTrace();}
			}

			String key=props.getProperty("FLICKR_KEY");
			String svr=props.getProperty("FLICKR_URL");
			REST rest;
			try {
					rest = new REST();
					rest.setHost(svr);
					// Initialize Flickr object with key and rest
					Flickr flickr=new Flickr(key,rest);
					Flickr.debugStream=false;
				    SearchParameters searchParams=new SearchParameters();
				    searchParams.setSort(SearchParameters.INTERESTINGNESS_DESC);
				    // Initialize PhotosInterface object
				    PhotosInterface photosInterface=flickr.getPhotosInterface();	    
				    PhotoList photoList = photosInterface.getRecent(obtainedFromDB < n ? (numResults - obtainedFromDB) : (numResults - n), 1);
					
					if(photoList!=null){
					       for(int i=0;i<photoList.size();i++){
						          Photo photo=(Photo)photoList.get(i);
						          String url = photo.getMediumUrl();
						          Img tmp = new Img(photo.getTitle(), url, url, photo.getUrl(), url, true);  
						          imgs.add(tmp);
						    }
					  }else{}
			 }

			catch (ParserConfigurationException e) {e.printStackTrace();} 
			catch (SAXException e) {e.printStackTrace();} 
			catch (FlickrException e) {e.printStackTrace();}

							
			// Close the connection
			try {connection.close();} catch (SQLException e) {e.printStackTrace();}

			// Return the RSS
			Collections.shuffle(imgs);
			for(int i = 0; i < imgs.size(); i++){
				imgs.get(i).setGlobalRank(i);
			}
			
			Rss r = new Rss(this.getServletName(), req.getServerName(), req.getContextPath());		
			r.createRss(imgs);
			PrintWriter pw =  res.getWriter();
			pw.print(r.getRss());			
		}
}